
#include <iostream>
#include <unistd.h>
#include <sys/socket.h>
#include "log.hpp"
#include <string>
#include <cstring>
#include <arpa/inet.h>
#include "Task.hpp"

void Menu(char *argv[])
{
    std::cout << argv[0] << "  [ip] " << " [port] " << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Menu(argv);
        exit(1);
    }

    std::string ip = argv[1];
    uint16_t port = std::stoi(argv[2]);

    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    inet_aton(ip.c_str(), &server.sin_addr);

    while (1)
    {
        int cnt = 0, n = 0 , sockfd = -1;
        const int max_cnt = 6;
        do
        {
            // 1.创建套接字
            sockfd = socket(AF_INET, SOCK_STREAM, 0);
            if (sockfd < 0)
            {
                std::cerr << " socket failed ";
                exit(2);
            }
            n = connect(sockfd, (sockaddr *)&server, sizeof(server));
            if (n < 0)
            {
                std::cout << "connet failed : " << cnt++ << std::endl;
                sleep(1);
            }
            else
                break;
        } while (cnt < max_cnt);
        if (cnt == max_cnt)
        {
            std::cout << "server error" << std::endl;
            return 0;
        }

        // 3.进行通信
        std::string message;
        char buffer[1024];
        while (1)
        {
            std::cout << "Please Enter@";
            std::getline(std::cin, message);
            write(sockfd, message.c_str(), message.size());
            n = read(sockfd, buffer, sizeof(buffer) - 1);
            if (n > 0)
            {
                buffer[n] = 0;
                std::cout << buffer << std::endl;
            }
            else
                break;

            if (message == "quit")
            {
                close(sockfd);
                return 0;
            }
        }
    }

    return 0;
}
